var express = require("express");
var router = express.Router();
let myQuery = require("../tools/db")
let { apiUrl, jwtsuo } = require("../tools/config")
let { jwtVerify } = require('../tools/token')
const timeStamp = require('time-stamp')
const path = require('path')
const fs = require('fs')
const formidable = require('formidable');
const { ok } = require("assert");

//所有的用户中心的访问 都要带着 token 所以token的验证中间件 要写在最前面
//验证token的中间件
router.use((req, res, next) => {
    let token = req.headers.authorization
    let obj = jwtVerify(token, jwtsuo)
    if (!obj) {
        next({ code: 200, msg: "请先登录" })
        return
    }
    req.mid = obj.mid;
    next()
})
//获取用户信息
router.get('/userinfo', async (req, res, next) => {
    let sql=`SELECT realname,username,sex,birthdate,city,CONCAT('${apiUrl}','avatar/',head_photo_url)AS headurl,
    createdate,nicheng FROM e_member WHERE mid='${req.mid}';`;
    let [err,result]=await myQuery(sql)
    if(err){
        next({code:500,msg:err})
        return
    }
    result[0].sex=result[0].sex==1?true:false
    let times=new Date(Number(result[0].birthdate))
    let Y=times.getFullYear()
    let M=times.getMonth()+1
    let D=times.getDate()
    function numDouble(num){
        return num>10?num:''+num
    }
    result[0].birthdate=`${Y}/${numDouble(M)}/${numDouble(D)}`
    
    res.send({code:200,msg:'ok',result})
})

router.post('/upload', (req, res, next) => {
    //上传图片
    let form = formidable({
        uploadDir: path.join(__dirname, '../uploads/avatar'),
        keepExtensions: true

    })
    form.parse(req, async(err, fields, files) => {
        let oldPath = files.upimg.filepath
        //创建新文件名
        let newName = timeStamp('YYYYMMDDHHmmss') + (Math.random() + '').slice(2, 10) + path.extname(oldPath)
        //使用新文件名拼接新路径
        let newPath = path.join(__dirname, '../uploads/avatar', newName)
        //新路径 替换老路径
        fs.renameSync(oldPath, newPath)

        //将新图片名 更新到数据库中
        let sql = `UPDATE e_member SET head_photo_url='${newName}' WHERE mid='${req.mid}';`

        let [err1,result]=await myQuery(sql)
        if(err){
            next({code:500,msg:err1})
            return
        }

        if(result.affectedRows>0){
            res.send({code:200,msg:'ok',headurl:apiUrl+'avatar/'+newName})
        }else{
            next({code:500,msg:"请稍后再试"})
        }
    })

})

router.put('/updateinfo',async (req, res, next) => {
    let {realname,sex,birthdate,nicheng}=req.body;
    birthdate=Date.parse(birthdate)
    console.log(sex);
    sex=Number(sex)
    console.log(sex);
    let sql=`UPDATE e_member SET realname='${realname}',sex=${sex},birthdate='${birthdate}',nicheng='${nicheng}' 
    WHERE mid='${req.mid}';`;
    let [err,result]=await myQuery(sql)
    if(err){
        next({code:500,msg:err})
        return
    }
    if(result.affectedRows>0){
        res.send({code:200,msg:'ok,修改成功'})
    }else{
        next({code:500,msg:"请稍后再试"})
    
    }  
})
router.get('/indent', async(req, res, next) => {
    let{pagenum=4,page=1}=req.query
    let startnum=(page-1)*pagenum;
    let sql=`SELECT COUNT(*)AS totals FROM e_order WHERE mid='${req.mid}';`
    let [,[{totals}]]=await myQuery(sql)
    let allpage=Math.ceil(totals/pagenum)
    let sql1=`SELECT e_course.id,e_course.cid,title,CONCAT('${apiUrl}','course/',image_src)AS image_src,price,type,type_name,area_name,grade_name,subject_name FROM e_order JOIN e_course ON e_order.cid=e_course.cid WHERE mid='${req.mid}' LIMIT ${startnum},${pagenum};`
    let[err,result]=await myQuery(sql1)
    if(err){
        next({code:500,msg:err})
        return
    }
    res.send({code:200,msg:'ok',pagenum,page,allpage,totals,result})
})


module.exports = router